package org.shock.ss.sms.action.system;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import com.opensymphony.xwork2.ActionContext;
import org.shock.ss.sms.commons.annotation.RightAnno;
import org.shock.ss.sms.bean.Page;
import org.shock.ss.sms.bean.Pager;
import org.shock.ss.sms.commons.db.DbTools;
import org.shock.ss.sms.commons.utils.ParamsUtil;
import org.shock.ss.sms.commons.utils.Util;
import org.shock.ss.sms.bean.system.Dept;
import org.shock.ss.sms.bean.system.Dic;
import org.shock.ss.sms.bean.system.User;
import org.shock.ss.sms.bean.system.UserInfor;
import org.shock.ss.sms.commons.dao.DaoFactory;
import org.shock.ss.sms.dao.system.impl.DicDaoImpl;
import org.shock.ss.sms.dao.system.impl.UserDaoImpl;
import org.shock.ss.sms.service.system.DicService;
import org.shock.ss.sms.service.system.UserService;
import org.shock.ss.sms.service.system.impl.DicServiceImpl;
import org.shock.ss.sms.service.system.impl.UserServiceImpl;
import org.shock.ss.sms.commons.utils.Encryption;
import org.shock.ss.sms.action.BaseAction;

/**
 * 用户管理action
 * 
 * @author jile
 * 
 */
public class UserAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	/** 获得service */
	private UserService us = new UserServiceImpl((UserDaoImpl) DaoFactory.getDao("UserDao"));
	private DicService dicService = new DicServiceImpl((DicDaoImpl) DaoFactory.getDao("DicDao"));
	private User user = new User();
	private List list = new ArrayList();
	private Integer node;
	private Dept dept = new Dept();// 所属部门id
	private String op = "";// 操作方式普通请求 或ajax请求
	private Map map = new HashMap();
	private String oldmm;
	private Map<String, List<Map<String, String>>> zdsMap = new HashMap<String, List<Map<String, String>>>();// 存储数据字典数据用
	private Map<String, List<Map<String, String>>> zdsMap2 = new HashMap<String, List<Map<String, String>>>();// 存储数据字典数据用
	private List shiList = new ArrayList();
	private List shiList2 = new ArrayList();
	private List quList = new ArrayList();
	private List quList2 = new ArrayList();
	private List yylxList = new ArrayList();
	private String whereSql;// 用户的查找条件
	private String query = "0";

	/**
	 * @return the shiList
	 */
	public List getShiList() {
		return shiList;
	}

	/**
	 * @param shiList
	 *            the shiList to set
	 */
	public void setShiList(List shiList) {
		this.shiList = shiList;
	}

	/**
	 * @return the quList
	 */
	public List getQuList() {
		return quList;
	}

	/**
	 * @param quList
	 *            the quList to set
	 */
	public void setQuList(List quList) {
		this.quList = quList;
	}

	@RightAnno(rightNote = "用户管理")
	public String userAdmin() throws Exception {
		return SUCCESS;
	}

	@RightAnno(rightNote = "查看用户")
	public String viewUser() throws Exception {
		if (null == user.getId()) {
			user.setId(getUserInfor().getId());
		}
		String[] zds = { "JZ", "JX", "ZW", "XL", "ZHUANYE", "RYZT" };
		String[] zds2 = { "SHENG" };
		zdsMap = dicService.getDataDictionaryMap(zds);
		zdsMap2 = dicService.getDataDictionaryMap2(zds2);
		shiList = DbTools.getList("select code,value from " + Dic.getTable()
				+ " where pcode='SHI' and min=(select jzdz_sheng from  " + User.getTable() + " where id="
				+ user.getId() + ")");
		System.out.println("select code,value from " + Dic.getTable()
				+ " where pcode='SHI' and min=(select jzdz_sheng from  " + User.getTable() + " where id="
				+ user.getId() + ")");
		shiList2 = DbTools.getList("select code,value from " + Dic.getTable()
				+ " where pcode='SHI' and min=(select hu_sheng from  " + User.getTable() + " where id=" + user.getId()
				+ ")");
		quList = DbTools.getList("select code,value from " + Dic.getTable()
				+ " where pcode='QU' and min=(select jzdz_shi from  " + User.getTable() + " where id=" + user.getId()
				+ ")");
		quList2 = DbTools.getList("select code,value from " + Dic.getTable()
				+ " where pcode='QU' and min=(select hu_shi from  " + User.getTable() + " where id=" + user.getId()
				+ ")");
		map = us.view("select y.*,d.bmqc as deptname from " + User.getTable() + " y left join " + Dept.getTable()
				+ " d on y.bmid=d.id where y.id=" + user.getId());
		return SUCCESS;
	}

	/**
	 * 增加或更新用户 根据bean 的id进行判断，如果id为null则为增加，否则为更新。
	 * 
	 * @return
	 * @throws Exception
	 */
	@RightAnno(rightNote = "用户变更", islog = true)
	public String saveUser() throws Exception {
		BeanUtils.populate(user, map);
		if (user.getId() == null || user.getId() == 0) {
			addUser();
		} else {
			Set<String> set = map.keySet();
			for (String key : set) {
				if ("bmid".equals(key)) {
					// System.out.println(key + "=>" + ((String[])
					// map.get(key))[0]);
					prjlog.setContent("部门变更: " + user.getYgxm() + " 由【" + ((String[]) map.get("deptname_old"))[0]
							+ "】变更至【" + ((String[]) map.get("deptname"))[0] + "】");
					prjlog.setBgcontent("|" + user.getId() + "|" + "bmid" + "|" + ((String[]) map.get("bmid"))[0] + "|"
							+ ((String[]) map.get("bmid_old"))[0] + "|");
					// System.out.println(ReflexUtils.rwritertoString(prjlog));
				}
			}
			updateUser();
		}
		if ("ajax".equals(op)) {
			return "ajxsuccess";
		}
		return SUCCESS;
	}

	@RightAnno(rightValue = "addUser", rightNote = "用户添加")
	public String addUser() throws Exception {
		if (action.equals("before")) {// 显示添加页面
			map = new HashMap<String, String>();
			map.put("bmid", dept.getId());
			map.put("deptname", dept.getBmmc());
			return "before";
		}
		user.setRoleids("-1,100000000001");// 默认为学员
		user.setYgmm(Encryption.getEncrypt("1111"));// 初始密码为1
		us.add(user);
		message = "添加成功！";
		jmpUrl = "listUser.do?dept.id=" + dept.getId();
		return SUCCESS;
	}

	@RightAnno(rightValue = "updateUser", rightNote = "修改用户")
	public String updateUser() throws Exception {
		if (action.equals("before")) {// 显示添加页面
			String sql = "select y.*,d.bmmc as deptname from " + User.getTable() + " y left join " + Dept.getTable()
					+ " d on y.bmid=d.id where y.id=" + user.getId();
			System.out.println(sql);
			map = us.view(sql);
			return "before";
		}
		// System.out.println(ReflexUtils.rwritertoString(user));
		us.update(user);
		message = "更新成功！";
		jmpUrl = "listUser.do?dept.id=" + dept.getId();
		return SUCCESS;
	}

	@RightAnno(rightNote = "用户列表")
	public String listUser() throws Exception {
		UserInfor userinfor = getUserInfor();
		/* 如果不是系统超级管理员或者市局管理员，则只能看到本部门及以下单位 */
		System.out.println(userinfor.getRolecodes());
		if (userinfor.getIsadmin() != 1 && !userinfor.getRolecodes().contains("xfadmin")
				&& !userinfor.getRolecodes().contains("sjld") && !userinfor.getRolecodes().contains("qjdack")) {
			String bmbh = "";
			if (userinfor.getRolecodes().contains("bmadmin")) {
				System.out.println(dept.getId());
				bmbh = DbTools.getString("select bmbh from " + Dept.getTable() + " where id=" + dept.getId());
			} else {
				bmbh = DbTools.getString("select bmbh from " + Dept.getTable() + " where id=" + userinfor.getBmid());
			}
			if (null == bmbh || "".equals(bmbh)) {
				bmbh = DbTools.getString("select bmbh from " + Dept.getTable() + " where id=" + userinfor.getBmid());
			}
			sqladd.append(" and bmid in (select id from " + Dept.getTable() + " where bmbh like '" + bmbh + "%')");
			if (null != dept.getId() && dept.getId() != 0) {
				dept.setId((dept.getId() == 34000000 ? userinfor.getBmid() : dept.getId()));
			}
		}
		Pager pager = new Pager();
		if (null != dept.getId() && dept.getId() != 0 && !"1".equals(query)) {
			sqladd.append(" and bmid=" + dept.getId());
		}
		if (null != user) {
			if (!Util.isEmpty(user.getYgxm())) {
				sqladd.append(" and ygxm like '%" + user.getYgxm().trim() + "%'");
			}
			if (!Util.isEmpty(user.getYgzh())) {
				sqladd.append(" and ygzh like '" + user.getYgzh().trim() + "%'");
			}
		}
		whereSql = sqladd.toString();
		String sul = ParamsUtil.transParams(getRequest().getParameterMap());
		String sqlcount = "select count(1) from " + User.getTable() + " where 1=1 " + sqladd;
		String sql = "select * from " + User.getTable() + " where 1=1 " + sqladd;
		System.out.println(sql);
		pager = us.list("asc", "paixu,id", pageno, rownum, sqlcount, sql);
		list = pager.getList();
		Page page = new Page();
		page.setPageString(pager.getTotalCount(), rownum, pageno, pagerow, sul);
		pageStr = page.getPageString();
		return SUCCESS;
	}

	@RightAnno(rightValue = "delUser", rightNote = "删除用户")
	public String delUser() throws Exception {
		String sql = "delete from " + User.getTable() + " where id =" + user.getId();
		us.del(sql);
		message = "删除成功！";
		jmpUrl = "listUser.do?dept.id=" + dept.getId();
		return SUCCESS;
	}

	@RightAnno(rightValue = "resetPwd", rightNote = "重置用户密码")
	public String resetPwd() throws Exception {
		String sql = "update " + User.getTable() + " set ygmm='" + Encryption.getEncrypt("1111") + "' where id ="
				+ user.getId();
		DbTools.doSql(sql);
		message = "重置密码为：1111！";
		jmpUrl = "listUser.do?dept.id=" + dept.getId();
		return SUCCESS;
	}

	@RightAnno(rightValue = "userRole", rightNote = "用户角色")
	public String userRole() throws Exception {
		String sql = "select * from " + User.getTable() + " where id=" + user.getId();
		Map map = us.view(sql);
		BeanUtils.populate(user, map);
		return SUCCESS;
	}

	@RightAnno(rightNote = "个人设定")
	public String myInfo() throws Exception {
		if ("before".equals(action)) {
			map = us.view("select y.*,d.bmqc as deptname from " + User.getTable() + " y left join " + Dept.getTable()
					+ " d on y.bmid=d.id where y.id=" + getUserInfor().getId());
			return "before";
		}
		if ("changepwd".equals(action)) {
			UserInfor userinfor = getUserInfor();
			String sql = "select count(1) from " + User.getTable() + " where ygzh='" + userinfor.getYgzh() + "'"
					+ " and ygmm='" + Encryption.getEncrypt(oldmm) + "' ";
			if (DbTools.getInt(sql) > 0) {
				BeanUtils.populate(user, map);
				user.setId(userinfor.getId());
				user.setYgmm(Encryption.getEncrypt(user.getYgmm()));
				us.update(user);
				message = "密码修改成功！";
				return SUCCESS;
			} else {
				message = "原密码错误！";
				return SUCCESS;
			}
		}
		BeanUtils.populate(user, map);
		us.update(user);
		message = "更新成功！";
		return SUCCESS;
	}

	/**
	 * 处理用户登录请求
	 * 
	 * @return
	 * @throws Exception
	 */
	@RightAnno(rightNote = "用户登录", islog = true)
	// islog为true表示进行日志记录
	public String doLogin() throws Exception {
		user.setYgzh(user.getYgzh().trim());
		UserInfor userinfor = us.checkUser(user.getYgzh().trim(), user.getYgmm());
		if (null == userinfor) {
			// 记录日志
			prjlog.setContent("登录失败");
			prjlog.setBgcontent("账号：" + user.getYgzh() + "密码：" + user.getYgmm());
			if ("ajax".equals(op)) {
				jsonString="{success:false,message:'账号或密码错误，登录失败！'}";
				return "ajxsuccess";
			}
			return "login";
		} 
			userinfor.setYgip(getRequest().getRemoteAddr());
			getSession().setAttribute("userinfor", userinfor);
			// WebRalasafe.setCurrentUser(getRequest(), userinfor.toRalaUser());
			// 记录日志
			prjlog.setContent("登录成功");
			prjlog.setBgcontent("账号：" + user.getYgzh() + "密码：" + user.getYgmm());
			if ("ajax".equals(op)) {
				return "ajxsuccess";
			}
			return "success";
	}

	@RightAnno(rightNote = "用户登出", islog = true)
	public String doLogout() {
		Map<String, Boolean> cfdlIpMap = (Map<String, Boolean>) ActionContext.getContext().getApplication().get(
				"cfdlIpMap");
		cfdlIpMap.put(getUserInfor().getYgip(), false);
		getSession().invalidate();
		Cookie[] cookies = getRequest().getCookies();
		for (int i = 0; i < cookies.length; i++) {
			cookies[i].setMaxAge(0);
			cookies[i].setPath(null);
		}
		prjlog.setContent("登出成功");
		System.gc();
		return "login";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	public Integer getNode() {
		return node;
	}

	public void setNode(Integer node) {
		this.node = node;
	}

	public String getOp() {
		return op;
	}

	public void setOp(String op) {
		this.op = op;
	}

	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;
	}

	public String getOldmm() {
		return oldmm;
	}

	public void setOldmm(String oldmm) {
		this.oldmm = oldmm;
	}

	/**
	 * @return the zdsMap
	 */
	public Map<String, List<Map<String, String>>> getZdsMap() {
		return zdsMap;
	}

	/**
	 * @param zdsMap
	 *            the zdsMap to set
	 */
	public void setZdsMap(Map<String, List<Map<String, String>>> zdsMap) {
		this.zdsMap = zdsMap;
	}

	/**
	 * @return the zdsMap2
	 */
	public Map<String, List<Map<String, String>>> getZdsMap2() {
		return zdsMap2;
	}

	/**
	 * @param zdsMap2
	 *            the zdsMap2 to set
	 */
	public void setZdsMap2(Map<String, List<Map<String, String>>> zdsMap2) {
		this.zdsMap2 = zdsMap2;
	}

	/**
	 * @return the shiList2
	 */
	public List getShiList2() {
		return shiList2;
	}

	/**
	 * @param shiList2
	 *            the shiList2 to set
	 */
	public void setShiList2(List shiList2) {
		this.shiList2 = shiList2;
	}

	/**
	 * @return the quList2
	 */
	public List getQuList2() {
		return quList2;
	}

	/**
	 * @param quList2
	 *            the quList2 to set
	 */
	public void setQuList2(List quList2) {
		this.quList2 = quList2;
	}

	public String getWhereSql() {
		return whereSql;
	}

	public void setWhereSql(String whereSql) {
		this.whereSql = whereSql;
	}

	/**
	 * @return the yylxList
	 */
	public List getYylxList() {
		return yylxList;
	}

	/**
	 * @param yylxList
	 *            the yylxList to set
	 */
	public void setYylxList(List yylxList) {
		this.yylxList = yylxList;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

}
